import { forEachValueKey } from "./utils";
import { computed } from "vue";

export function createMutations(store, mutations) {
  forEachValueKey(mutations, (mutationFn, mutationKey) => {
    // mutationFn -> (store, payload) -> store._mutations(payload)
    store._mutations[mutationKey] = (payload) => {
      mutationFn.apply(store, [store.state, payload]);
    };
  });
}

export function createActions(store, actions) {
  forEachValueKey(actions, (actionFn, actionKey) => {
    // mutationFn -> (store, payload) -> store._mutations(payload)
    store._actions[actionKey] = (payload) => {
      actionFn.apply(store, [store, payload]);
    };
  });
}

export function createGetters(store, getters) {
  store.getters = {};

  forEachValueKey(getters, (getterFn, getterKey) => {
    // store.gettter.xxx -> return -> getterFn() 的执行结果

    const getterFnComputed = computed(() => getterFn(store.state, store.getters))

    Object.defineProperty(store.getters, getterKey, {
      get() {
        // store.getters.filteredTodos
        return getterFnComputed.value;
      },
    });
  });
}

export function createCommitFn(store, commit) {
  store.commit = function (type, payload) {
    commit.apply(store, [type, payload]);
  };
}

export function createDispatchFn(store, dispatch) {
  store.dispatch = function (type, payload) {
    dispatch.apply(store, [type, payload]);
  };
}
